#! usr/bin/python
# -*- coding:utf-8 -*-

import tkinter
import tkinter.ttk
import serial
import tkinter.ttk
print(dir(serial))
import threading
import re
import time
import serial.tools.list_ports

def dianhuaben():
    var.set("")
    if port_status == True:
        command_list = ['AT+CPBS=?', 'AT+CPBS="SM"', 'AT+CPBR=?', 'AT+CPBR=1,8']
        for command in command_list:
            open_port.write(str(command).encode('utf-8') + b'\r\n')
            read_result = open_port.readlines()
            print(read_result)
            lianxi_list = []
            for j in read_result[1:-2]:
                lianxi_ren = j.decode('utf-8').rstrip().split('+CPBR: ')[-1]
                if len(lianxi_ren) != 0:
                    lianxi_list.append(lianxi_ren + '\n')

            info1 = "".join(lianxi_list)
            info2 = "我的电话本 \n" + info1
            print('dian_hua_list ====>: ', info2)
            var.set(info2)
    #open_port.close()

def bohao():
    global open_port
    get_info = result_entry.cget('text')
    print('telephone number ====: ', get_info)
    if len(get_info) > 4:
        if ('#' or '*') not in get_info:
            #open_port = serial.Serial(str(device_list[0]), baudrate=9600, timeout=1)
            #port_status = open_port.isOpen()
            #if port_status == True:
            command = 'ATD' + get_info + ';'
            open_port.write(str(command).encode('utf-8') + b'\r\n')
            read_result = open_port.readlines()
            print(read_result)
            var.set("正在呼叫 \n" + str(get_info))
            #open_port.close()

def guaduan():
    var.set("")
    global port_status
    if port_status == True:
        command = 'AT+CHUP'
        open_port.write(str(command).encode('utf-8') + b'\r\n')
        read_result = open_port.readlines()
        print('read_result ====>: ',  type(read_result), read_result)
        #var.set(read_result) #13925810705
        var.set('已挂断')
        try:
            fa_song_zhe = str(a2[1]).split('","","')[0].split('"')[-1]
            fa_song_time = str(a2[1]).split('","","')[1].split('+')[0]
            duan_xin_num = str(a2[2]).split("b'")[-1].split("\\")[0]
            str_len = int(len(duan_xin_num) / 4)
            message_list = []
            for char_index in range(str_len):
                four_number = r'\u' + str1[char_index * 4: (char_index + 1) * 4]
                han_zi = four_number.encode().decode("unicode_escape")
                message_list.append(han_zi)
            message = ''.join(message_list)
            #message_len =
            message_show = '[发件人]: %s \n' % (fa_song_zhe) + '[发送时间]: %s \n' % (
                fa_song_time[0]) + '[信息内容]: %s \n' % (message)

            print(fa_song_zhe)
            print(fa_song_time)
            print(message)
            print(message_show)
            print('message_show =====>>>: ', message_show)
        except:
            pass
    #print(read_result)

    #open_port.close()

def xinhaoqiangdu():
    var.set("")
    #open_port = serial.Serial(str(device_list[0]), baudrate=9600, timeout=1)
    #port_status = open_port.isOpen()
    if port_status == True:
        command = 'AT+CSQ'
        open_port.write(str(command).encode('utf-8') + b'\r\n')
        read_result = open_port.readlines()
        print(read_result)
        qiang_du = str(read_result[2]).split('+CSQ: ')[-1].split(',')[0]
        xin_hao_value = int(qiang_du) * 2 - 113
        print(qiang_du, xin_hao_value)
        if xin_hao_value >= -119 and xin_hao_value <= -95:
            xin_hao_du = '当前信号差'
        if xin_hao_value >= -93 and xin_hao_value <= -85:
            xin_hao_du = '当前信号一般'
        if xin_hao_value >= -83 and xin_hao_value <= -75:
            xin_hao_du = '当前信号好'
        if xin_hao_value >= -73 and xin_hao_value <= -53:
            xin_hao_du = '当前信号强'
        var.set(xin_hao_du + ',信号值为:' + str(xin_hao_value) + 'dBm')
    #open_port.close()

def yun_ying_shang():
    #open_port = serial.Serial(str(device_list[0]), baudrate=9600, timeout=1)
    #port_status = open_port.isOpen()
    if port_status == True:
        command = 'AT+COPS?'  # 'AT+CNUM?'
        open_port.write(str(command).encode('utf-8') + b'\r\n')
        read_result = open_port.readlines()
        print(read_result)
        try:
            command = 'AT+COPS?' # 'AT+CNUM?'
            open_port.write(str(command).encode('utf-8') + b'\r\n')
            read_result = open_port.readlines()
            print(read_result)
            vendor = str(read_result[2]).split('"')[1]
            if vendor == "CHINA MOBILE":
                top_var.set('中国移动')
            else:
                top_var.set('其他供应商')
        except:
            top_var.set('无SIM卡')
    #open_port.close()

def current_time():
    global port_status
    #open_port = serial.Serial(str(device_list[0]), baudrate=9600, timeout=1)
    #port_status = open_port.isOpen()
    if port_status == True:
        command2 = 'AT+CCLK?' # 'AT+CNUM?'
        open_port.write(str(command2).encode('utf-8') + b'\r\n')
        read_result = open_port.readlines()
        print(read_result)
        net_time = str(read_result[2]).split('"')[1].split('+')[0].split(',')[-1]
        print(net_time)
        top2_var.set(str(net_time))
    #open_port.close()

def benjihaoma():
    global port_status
    var.set("")
    if port_status == True:
        command3 = 'AT+CNUM' # 'AT+CNUM?'
        open_port.write(str(command3).encode('utf-8') + b'\r\n')
        read_result = open_port.readlines()
        print(str(read_result[2]).split(',')[1])
        phone_number = str(read_result[2]).split(',')[1]
        var.set('本机号码为：\n' + phone_number)
    #open_port.close()

def clearn_label():
    var.set('')

def show_shi_zi(buttonString):
    button_value = var.get()
    if button_value == 0:
        button_value = ''
    var.set(button_value + buttonString)
    #print(buttonString)

def delete_1_char():
    var.set(str(var.get()[:-1]))

try:
    device_list = []
    a = serial.tools.list_ports.comports()
    for i in a:
        ser = str(i).split(' - ')[0]
        device_list.append(ser)
        print(ser)
except:
    print('无设备接入，请插入GPRS设备')

def www_go():
    command_list = ['AT+HTTPINIT', 'AT+HTTPPARA="CID","1"',
                    'AT+HTTPPARA="URL","https://www.mca.gov.cn/article/sj/xzqh/1980/"',
                    'AT+HTTPACTION=0', 'AT+HTTPREAD=1, 500',  'AT+HTTPTERM',  'AT+SAPBR=0, 1']
    port_status = open_port.isOpen()
    if port_status == True:
        for command in command_list:
            try:
                open_port.write(str(command).encode('utf-8') + b'\r\n')
                read_result = open_port.readlines()
                print(read_result)
            except:
                pass

def open_liuliang():
    global open_port
    command_list = ['AT+SAPBR=3,1,"APN","cmnet"', 'AT+SAPBR=3,1,"PHONENUM","18710811211"', 'AT+SAPBR=4,1',
                    'AT+SAPBR=5,1', 'AT+SAPBR=1,1', 'AT+SAPBR=2,1'] #, 'wo shi shui?']
    #open_port = serial.Serial(str(device_list[0]), baudrate=9600, timeout=6)
    #port_status = open_port.isOpen()
    if port_status == True:
        for command in command_list:
            try:
                open_port.write(str(command).encode('utf-8') + b'\r\n')
                read_result = open_port.readlines()
                print(read_result)
            except:
                pass

def short_message_revice():
    command_list = ['AT+CPMS=?', 'AT+CPMS="SM"']
    message_list = []
    if port_status == True:
        for command in command_list:
            try:
                open_port.write(str(command).encode('utf-8') + b'\r\n')
                read_result = open_port.readall().decode('utf-8')
                time.sleep(2)
                print(read_result)
                message_list.append(read_result)
            except:
                pass
    try:
        pattern1 = '[0-9A-F][0-9A-F][0-9A-F][0-9A-F][0-9A-F][0-9A-F][0-9A-F][0-9A-F]+'
        pattern2 = '\d{2}:\d{2}:\d{2}'
        key_txt = re.findall(pattern1, str(message_list[0]))
        key_time = re.findall(pattern2, str(message_list[0]))
        str_len = int(len(key_txt[0]) / 4)
        message_list = []
        for char_index in range(str_len):
            four_number = r'\u' + key_txt[0][char_index * 4: (char_index + 1) * 4]
            han_zi = four_number.encode().decode("unicode_escape")
            message_list.append(han_zi)
        message = ''.join(message_list)
        message_show = '[发送时间]: %s \n' % (key_time) + '[信息内容]: %s \n' % (message)
        print(message_show)
        var.set('       短信中心\n' + message_show)
    except:
        pass




'''
def jie_ting():
    command_list1 = ['AT+CMGF=0', 'AT+CPAS']
    open_port = serial.Serial(str(device_list[0]), baudrate=9600, timeout=1)
    port_status = open_port.isOpen()
    if port_status == True:
        for command in command_list1:
            try:
                open_port.write(str(command).encode('utf-8') + b'\r\n')
                read_result = open_port.readlines()
                print(read_result)
                status = read_result[-3]
                print('statue', type(status), status)
                if "+CPAS" in str(status):
                    result = str(status).split(':')[-1][1:2]
                    print('-------------------', str(result), type(str(result)))
                    if result == '0':
                        open_port.write(str("ATA").encode('utf-8') + b'\r\n')
                        read_result = open_port.readlines()
                        print(read_result)
            except:
                pass

jie_ting()
'''

def www_go():
    #open_port = serial.Serial(str(device_list[0]), baudrate=9600, timeout=1)
    #command_list = ['AT+CGATT?', 'AT+SAPBR=3,1,"CONTYPE","GPRS"', 'AT+SAPBR=3,1,"APN","CMNET"', 'AT+SAPBR=1,1',
    #                'AT+CIPGSMLOC=1,1', 'AT+CIPGSMLOC=2,1','AT+SAPBR=0,1']
    command_list = ['AT+CPBR=?', 'AT+CPBR=2']
    port_status = open_port.isOpen()
    if port_status == True:
        for command in command_list:
            try:
                open_port.write(str(command).encode('utf-8') + b'\r\n')
                read_result = open_port.readlines()
                print(read_result)
            except:
                pass

def fa_song_message():
    phone_number = entry1.get()
    message1 = text3.get("1.0", "end-1c")
    print('message1 ===>: ', message1)
    print('phone_number ===>:', phone_number)
    print((message1 + chr(26)).encode())

    '''
    def send_sms(phone_number, message):
        open_port.write('AT+CMGF=1\r\n'.encode())
        print('open_port1 ====>: ', open_port.readlines())
        time.sleep(0.2)
        open_port.write('AT+CMGS="{}"\r\n'.format(phone_number).encode())
        print('open_port2 ====>: ', open_port.readlines())
        time.sleep(0.2)
        open_port.write('{}\r\n'.format(message).encode())
        print('open_port3 ====>: ', open_port.readlines())
        time.sleep(0.2)
        #while True:
        response = open_port.readline().decode().strip()
        print('response ========>: ', response)
        if response.startswith('+CMGS') or response.startswith('+CMS ERROR'):
            print(response)
                #break
    command_list = ['AT+CMGF=1', 'AT+CMGS="%s"' %(phone_number), (message1 + chr(26)).encode()]
    send_sms(phone_number, message1)
    '''
    command_list = ['AT+CMGF=0', 'AT+CSCS="GSM"', 'AT+CMGF=1', 'AT+CMGS="%s"' % (phone_number)]  # , message1]
    #command_list = ['AT+CMGF=0', 'AT+CMGS="%s"' %(phone_number)]#, message1]
    #port_status = open_port.isOpen()
    #if port_status == True:

    open_port.write(b'AT+CSCS="GSM"\r\n')
    read_result = open_port.readlines()
    print(read_result)
    open_port.write(b'AT+CMGF=1\r\n')
    read_result = open_port.readlines()
    print(read_result)
    open_port.write(b'AT+CMGS="13925810705"\r\n')
    read_result = open_port.readlines()
    print(read_result)
    open_port.write(str(message1).encode('utf-8') + b'\r\n')
    read_result = open_port.readlines()
    print(read_result)

    '''
    for command in command_list:
        try:
            open_port.write(str(command).encode('utf-8') + b'\r\n')
            read_result = open_port.readlines()
            print(read_result)
            time.sleep(0.3)
        except:
            pass
    time.sleep(0.3)
    open_port.write(str(message1).encode('utf-8') + b'\r\n')
    read_result = open_port.readlines()
    print(read_result)
    def send_at_command(command):
        open_port.write((command + '\r\n').encode())
        print('33333333333 =====> ' , open_port.readlines())
        time.sleep(0.5)
        response = b''
        while open_port.inWaiting() > 0:
            response += open_port.read(1)
        return response.decode().strip()

    def initialize_sim900a():
        response = send_at_command('AT')
        if response != 'OK':
            print('SIM900A模块未正常工作！')
            #return False

        # 设置短信模式为文本模式
        response = send_at_command('AT+CMGF=1')
        if response != 'OK':
            print('设置短信模式失败！')
            #return False

        # 设置短信字符集为GSM编码
        response = send_at_command('AT+CSCS="GSM"')
        if response != 'OK':
            print('设置短信字符集失败！')
           # return False

        #return True

    # 发送短信 #'AT+CMGS="13632754344"'
    def send_sms(phone_number, message):
        response = send_at_command('AT+CMGS="' + phone_number + '"')
        print('repose =====>: ', response)
        if response != '>':
            print('设置手机号码失败！')

        message_info = (message + chr(26)).encode()
        print('message_info =====>: ', message_info)
        open_port.write((message + chr(26)).encode())
        print('11111 ====>: ', open_port.readlines())
        time.sleep(2)
        response = b''
        while open_port.inWaiting() > 0:
            response += open_port.read(1)
        response = response.decode().strip()
        if response.endswith('ERROR'):
            print('发送短信失败！')
            return False
        return

    #if not initialize_sim900a():
    #    print('初始化SIM900A模块失败！')
        #exit()

    # 发送短信
    #phone_number = '手机号码'
    #message1 = 'Hello, World!'
    #if send_sms(phone_number, message1):
    #    print('短信发送成功！')
    #else:
    #    print('短信发送失败！')
    '''




root = tkinter.Tk()
root.title('模拟手机')
root.resizable(0, 0)
root.attributes('-topmost', 1)

top_var = tkinter.StringVar()
top2_var = tkinter.StringVar()
frame_top = tkinter.Frame()
result_entry_top1 = tkinter.Label(frame_top, width=12, height=1, textvariable=top_var)
result_entry_top1.grid(row=0, column=0, padx=2)
result_entry_top2 = tkinter.Label(frame_top, width=12, height=1, textvariable=top2_var)
result_entry_top2.grid(row=0, column=1, padx=2)
frame_top.grid(row=0, column=0, padx=2)

var = tkinter.StringVar()
frame_first = tkinter.Frame()

notebook =tkinter.ttk.Notebook(frame_first)

frame1 = tkinter.LabelFrame(frame_first, text='显示屏:')
result_entry = tkinter.Label(frame1, width=32, height=10, textvariable=var)
result_entry.grid(row=0, column=0, padx=2, pady=2)
frame1.grid(row=1, column=0, padx=2, pady=2)

frame2 = tkinter.LabelFrame(frame_first, text='编辑短信:')
#label_text = tkinter.Label(frame2, width=32, height=10, textvariable=var)
#label_text.grid(row=0, column=0, padx=2, pady=2)

text1 = tkinter.Label(frame2, text='发送人:')
text1.grid(row=0, column=0, padx=2, pady=2)
entry1 = tkinter.Entry(frame2)
entry1.grid(row=0, column=1, padx=2, pady=2)
text2_label = tkinter.Label(frame2, text='请输入信息内容按发送键发送')
text2_label.grid(row=1, column=0, columnspan=2, padx=2, pady=2)
text3 = tkinter.Text(frame2, height=9, width=32)
text3.insert('insert', 'how are you, this message from software phone, please ignore it, thanks')
text3.grid(row=2, column=0, columnspan=2, padx=2, pady=2)
frame1.grid(row=1, column=0, padx=2, pady=2)


notebook.add(frame1, text='  电话  ')
notebook.add(frame2, text='  短信  ')
notebook.grid()

frame2 = tkinter.LabelFrame(frame_first, text='键盘:')

button_bai = tkinter.Button(frame2, text='信号强度', width=9, command=xinhaoqiangdu)
button_bai.grid(row=0, column=0, padx=2, pady=2)
button_ce = tkinter.Button(frame2, text='电话本', width=9, command=dianhuaben)
button_ce.grid(row=0, column=1, padx=2, pady=2)
button_c = tkinter.Button(frame2, text='本机号码', width=9, command=benjihaoma)
button_c.grid(row=0, column=2, padx=2, pady=2)

button_bai = tkinter.Button(frame2, text='取消', width=9, command=clearn_label)
button_bai.grid(row=1, column=0, padx=2, pady=2)
button_ce = tkinter.Button(frame2, text='发送短信', width=9, command=fa_song_message)
button_ce.grid(row=1, column=1, padx=2, pady=2)
button_c = tkinter.Button(frame2, text='拨号', width=9, command=bohao)
button_c.grid(row=1, column=2, padx=2, pady=2)

button_dao = tkinter.Button(frame2, text='左翻页', width=9)
button_dao.grid(row=2, column=0, padx=2, pady=2)
button_fang = tkinter.Button(frame2, text='时间', width=9, command=current_time)
button_fang.grid(row=2, column=1, padx=2, pady=2)
button_sqrt = tkinter.Button(frame2, text='右翻页', width=9)
button_sqrt.grid(row=2, column=2, padx=2, pady=2)


button_dao = tkinter.Button(frame2, text='挂断', width=9, command=guaduan)
button_dao.grid(row=3, column=0, padx=2, pady=2)
button_fang = tkinter.Button(frame2, text='接收短信', width=9, command=short_message_revice)
button_fang.grid(row=3, column=1, padx=2, pady=2)
button_sqrt = tkinter.Button(frame2, text='接听', width=9)
button_sqrt.grid(row=3, column=2, padx=2, pady=2)

button_7 = tkinter.Button(frame2, text='1', textvariable=1, width=9, command=lambda: show_shi_zi('1'))
button_7.grid(row=4, column=0, padx=2, pady=2)
button_8 = tkinter.Button(frame2, text='2', width=9, command=lambda: show_shi_zi('2'))
button_8.grid(row=4, column=1, padx=2, pady=2)
button_9 = tkinter.Button(frame2, text='3', width=9, command=lambda: show_shi_zi('3'))
button_9.grid(row=4, column=2, padx=2, pady=2)

button_4 = tkinter.Button(frame2, text='4', width=9, command=lambda: show_shi_zi('4'))
button_4.grid(row=5, column=0, padx=2, pady=2)
button_5 = tkinter.Button(frame2, text='5', width=9, command=lambda: show_shi_zi('5'))
button_5.grid(row=5, column=1, padx=2, pady=2)
button_6 = tkinter.Button(frame2, text='6', width=9, command=lambda: show_shi_zi('6'))
button_6.grid(row=5, column=2, padx=2, pady=2)

button_1 = tkinter.Button(frame2, text='7', width=9, command=lambda: show_shi_zi('7'))
button_1.grid(row=6, column=0, padx=2, pady=2)
button_2 = tkinter.Button(frame2, text='8', width=9, command=lambda: show_shi_zi('8'))
button_2.grid(row=6, column=1, padx=2, pady=2)
button_3 = tkinter.Button(frame2, text='9', width=9, command=lambda: show_shi_zi('9'))
button_3.grid(row=6, column=2, padx=2, pady=2)

button_fu = tkinter.Button(frame2, text='#', width=9, command=lambda: show_shi_zi('#'))
button_fu.grid(row=7, column=0, padx=2, pady=2)
button_0 = tkinter.Button(frame2, text='0', width=9, command=lambda: show_shi_zi('0'))
button_0.grid(row=7, column=1, padx=2, pady=2)
button_dian = tkinter.Button(frame2, text='*', width=9, command=lambda: show_shi_zi('*'))
button_dian.grid(row=7, column=2, padx=2, pady=2)
button_fun1 = tkinter.Button(frame2, text='打开流量', width=9, command=open_liuliang)
button_fun1.grid(row=8, column=0, padx=2, pady=2)
button_fun2 = tkinter.Button(frame2, text='上网页', width=9, command=www_go)
button_fun2.grid(row=8, column=1, padx=2, pady=2)
button_fun2 = tkinter.Button(frame2, text='关闭流量', width=9, command=www_go)
button_fun2.grid(row=8, column=2, padx=2, pady=2)

frame2.grid(row=2, column=0, padx=5, pady=5)
frame_first.grid(padx=5, pady=5)

device_list = []
a = serial.tools.list_ports.comports()
for i in a:
    print(i)
    ser = str(i).split(' - ')[0]
    device_list.append(ser)
    print(ser)

print('device_list ========>:  ', device_list)

open_port = serial.Serial(str(device_list[0]), baudrate=9600, timeout=1)
port_status = open_port.isOpen()
print('port_status =====>:  ', port_status)

try:
    yun_ying_shang()
except:
    pass

try:
    current_time()
except:
    pass

root.mainloop()

#open_port.close()

#thread1 = threading.Thread(target=interface_UI)
#thread2 = threading.Thread(target=short_message_revice)
#thread1.start()
#thread2.start()
#thread1.join()
#thread2.join()

#15072287903
#'AT+CMGS="+8613632754344"'
#'aa63155c328810a7dee1e8397726aae5'
#'1400760929'
#template_id = '1597586'
# dong 13925810705
# 1